package com.cooldatasoft.rest.servlet;

import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Map.Entry;
import java.util.Set;
import java.util.jar.Manifest;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.util.UrlPathHelper;

@Slf4j
@Component
public class RestServlet extends DispatcherServlet {
	private static final long serialVersionUID = 1L;

	private static final UrlPathHelper URL_PATH_HELPER = new UrlPathHelper();

	@Override
	protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			String requestUri = URL_PATH_HELPER.getRequestUri(request).replaceAll(request.getContextPath(), "");
			System.out.println(requestUri);
			log.trace("Requested URL : {} ", requestUri);
			if (requestUri.equalsIgnoreCase("/info")) {
				/**
				 * Used to serve version info and manifest details at CONTEXT_ROOT/info
				 */
				ServletContext application = getServletConfig().getServletContext();
				InputStream inputStream = application.getResourceAsStream("/META-INF/MANIFEST.MF");
				Manifest manifest = new Manifest(inputStream);
				PrintWriter pw = response.getWriter();

				Set<Entry<Object, Object>> entrySet = manifest.getMainAttributes().entrySet();
				for (Entry<Object, Object> currentEntry : entrySet) {
					pw.println(currentEntry);
				}
			} else {
				super.doService(request, response);
			}
		} catch (Exception e) {
			log.error("Exception Occured!", e);
		}
	}
}
